﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XrmLibrary.Enums;
using XrmLibrary.Extensions;

namespace XrmLibrary.Context
{
    public class LogContext
    {
        public LogType LogType { get; private set; }
        public String Message { get; private set; }
        public Object State { get; private set; }
        public Exception Exception { get; private set; }

        private LogContext(LogType logType, String message, Object state, Exception exception)
        {
            LogType = logType;
            Message = message;
            State = state;
            Exception = exception;
        }

        public static LogContext InstantiateDebug(Object state = null, Exception exception = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Debug, GetMessage(format, args), state, exception);
        }

        public static LogContext InstantiateSuccess(Object state = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Success, GetMessage(format, args), state, null);
        }

        public static LogContext InstantiateInfo(Object state = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Info, GetMessage(format, args), state, null);
        }

        public static LogContext InstantiateWarn(Object state = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Warn, GetMessage(format, args), state, null);
        }

        public static LogContext InstantiateError(Object state = null, Exception exception = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Error, GetMessage(format, args), state, exception);
        }

        public static LogContext InstantiateFatal(Object state = null, Exception exception = null, String format = null, params Object[] args)
        {
            return new LogContext(LogType.Fatal, GetMessage(format, args), state, exception);
        }

        private static String GetMessage(String format, params Object[] args)
        {
            return String.Format(format, args);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("TYPE: {0}", LogType.GetDescription());
            if(!String.IsNullOrEmpty(Message))
            {
                sb.AppendFormat(", MESSAGE: {0}", Message);
            }
            if(State != null)
            {
                sb.AppendFormat(", STATE: {0}", State);
            }
            if(Exception != null)
            {
                sb.AppendFormat(", EXCEPTION: {0}", Exception);
            }
            return sb.ToString();
        }
    }
}